/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.bef.core.scope;

import com.inspur.edp.bef.api.exceptions.BefException;
import com.inspur.edp.bef.api.exceptions.ErrorCodes;
import com.inspur.edp.bef.core.session.FuncSession;
import com.inspur.edp.bef.entity.exception.ExceptionLevel;
import com.inspur.edp.cef.api.scope.ICefScopeNodeParameter;
import com.inspur.edp.cef.core.scope.CefScopeNode;
import com.inspur.edp.cef.core.scope.CefScopeStack;

public class BefScopeStack extends CefScopeStack {

  private final FuncSession session;

  public BefScopeStack(FuncSession session) {
    this.session = session;
  }
  
  @Override
  public int getCount() {
    java.util.Stack<CefScopeNode> stack = session.getScopeNodeStack();
    return stack == null ? 0 : stack.size();
  }

  /**
   * 读取栈顶
   *
   * @return
   */
  @Override
  public CefScopeNode getTopNode() {
    return session.getScopeNodeStack().peek();
  }

  /**
   * 出栈
   */
  @Override
  public void pop() {
    session.getScopeNodeStack().pop();
  }

  /**
   * 入栈
   *
   * @param node
   */
  @Override
  public void push(CefScopeNode node) {
    if (session.getScopeNodeStack() == null) {
      session.setScopeNodeStack(new java.util.Stack<CefScopeNode>());
    }

    session.getScopeNodeStack().push(node);
  }

  public final void addScopeParameter(ICefScopeNodeParameter parameter) {
    CefScopeNode node = getTopNode();
    if (node == null) {
      throw new BefException(ErrorCodes.NoScope, "不存在有效批量处理", null, ExceptionLevel.Error);
    }
    node.setParameter(parameter);
  }
}
